package com.huafeng.utils;

import cn.hutool.core.util.StrUtil;
import com.google.common.io.Closer;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 花风
 * @date 2023/4/5 9:38
 * @Description http请求工具类
 */
public class HttpUtils {

    //不带参数的Get请求
    public static String doGet(String url){
        return doGet(url,null);
    }

    //Get请求携带参数 例如 www.baidu.com?name=jack
    public static String doGet(String url, Map<String,Object> params){
        Closer closer = Closer.create();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpClient = HttpClients.createDefault();
            closer.register(httpClient);
            //创建封装的URI对象，可以存放参数
            URIBuilder uriBuilder = new URIBuilder(url);
            if (params != null && params.size() > 0){
                for (Map.Entry<String, Object> objectEntry : params.entrySet()) {
                    uriBuilder.addParameter(objectEntry.getKey(), objectEntry.getValue().toString());
                }
            }

            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpResponse = httpClient.execute(httpGet);
            closer.register(httpResponse);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                //执行成功，获取结果
                HttpEntity entity = httpResponse.getEntity();
                return EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                closer.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return "";
    }

    //post请求不带参数
    public static String doPost(String url){
        return doPost(url,null);
    }

    //post请求携带Json参数
    public static String doPost(String url,String json,String contentType){
        Closer closer = Closer.create();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpClient = HttpClients.createDefault();
            closer.register(httpClient);

            HttpPost httpPost = new HttpPost(url);
            //绑定JSON参数
            if (json != null && json.length() > 0 && !StrUtil.isBlank(json)){
                StringEntity stringEntity = new StringEntity(json,contentType);
                httpPost.setEntity(stringEntity);
            }

            httpResponse = httpClient.execute(httpPost);
            closer.register(httpResponse);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                HttpEntity entity = httpResponse.getEntity();
                return EntityUtils.toString(entity);
            }
        }catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                closer.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return "";
    }

    //post请求携带表单参数
    public static String doPost(String url,Map<Object,Object> params){
        Closer closer = Closer.create();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;

        try {
            httpClient = HttpClients.createDefault();
            closer.register(httpClient);

            HttpPost httpPost = new HttpPost(url);
            if (params != null){
                //参数不为空时
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<Object, Object> objectObjectEntry : params.entrySet()) {
                    paramList.add(new BasicNameValuePair(objectObjectEntry.getKey().toString(), objectObjectEntry.getValue().toString()));
                }
                //模拟表单
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(formEntity);
            }

            //执行post请求
            httpResponse = httpClient.execute(httpPost);
            closer.register(httpResponse);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                //如果执行成功
                HttpEntity entity = httpResponse.getEntity();
                return EntityUtils.toString(entity);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                closer.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return "";
    }
}
